# Author: Br. Francis Therese Krautter -- br.ftherese(at)gmail.com

# Notes: This module will not work unless you have lilypond installed (http://www.lilypond.org) along with an account on the lilypond posterous blog.  

# The cURL statement reads the username and password from the user's .netrc file in their home directory when accessing Posterous.

# Though you may not find lilypond useful or interesting, this module could be easily modified to produce other kinds of command-line generated content (pdf files, sound files, images, video) that is automatically posted (via Posterous) on the Web with the respective link posted in the IRC channel. 

package cringer::lilypond;

use Time::localtime;

# lilypond.pm
# provides search functionality for cringer using the Posterous API

our $VERSION = '2.0';

sub said{
 my $self = $_[0];
 my $args = $_[1];
 my $me = $self->{nick};

 unless($args->{body} =~ /^lilypond: ?(.*)$/){ # if this isn't a lilypond query, we skip it.
  return;
 }

 @now = split /\s/, ctime();
 my @r; 
 my $lilydata = $1;
 $lilydata =~ s/system//g;
 my $filename = "$now[3]$now[4]";
 $filename =~ s/:/-/g;
 open FILE, ">/tmp/$filename\.ly" or die $!;
 print FILE '\\version "2.12.2"';
 print FILE "\n";
 print FILE "\\header { tagline = ##f } \n";
 print FILE "\\score { \n";
 print FILE $lilydata . "\n";
 print FILE "\\midi {} \n";
 print FILE "\\layout {} \n }";
 
 close FILE;

 system("cat /tmp/$filename.ly > /tmp/$filename.doc");

 my $result = `lilypond -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts --png '/tmp/$filename.ly' 2>&1`;
 open FILE, ">>/tmp/$filename\.doc";
 print FILE $result;
 close FILE;

 system("timidity -Ow $filename.midi");
 system("lame $filename.wav $filename.mp3");

# This curl request assumes that you have the proper username and password in your .netrc file

 my $curlrequest = qq~curl -D - -n -F "site_id=1147841" -F "autopost=0" -F "media[1]=\@/tmp/$filename.doc" -F "title=$filename" -F "media[2]=\@$filename.mp3" -F "media[0]=\@$filename.png" http://posterous.com/api/newpost~;

 system($curlrequest);
 system("rm *.png *.eps *.midi *.mp3 *.tex* *.wav *.count /tmp/*.ly /tmp/*.doc");

 push(@r, qq~lilypond file "$filename.ly" at http://lilypond.posterous.com/$filename~);
return @r;}
